package com.chen.internalcommon.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.chen.internalcommon.constant.TokenConstants;
import com.chen.internalcommon.dto.TokenResult;

import java.time.LocalDateTime;

/**
 * @author chenLiuPing
 **/
public class JwtUtils {

    // 艳
    private static final String SIGN = "#4!@chen8848%";

    private static final String JWT_KEY_PHONE = "phone";

    // 乘客和司机的手机号可能一样，为了区分
    private static final String JWT_KEY_IDENTITY = "identity";

    private static final String JWT_TOKEN_TIME = "tokenTime";

    private static final String TOKEN_TYPE = "tokenType";

    /**
     * 生成token
     * @param phone 电话号码
     * @param identity 身份 乘客或者司机
     * @param tokenType
     * @return
     */
    private static String generateToken(String phone, String identity, String tokenType) {
        // 根据map 过期时间 盐生成token

        // 由于token已经存储在了redis并设置了过期时间，所以这里就不用再设置过期时间了
//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.DATE, 1);
//        Date date = calendar.getTime();

        JWTCreator.Builder builder = JWT.create();
        builder.withClaim(JWT_KEY_PHONE, phone);
        builder.withClaim(JWT_KEY_IDENTITY, identity);
        builder.withClaim(TOKEN_TYPE, tokenType);
        // 防止每次生成的token一样
        builder.withClaim(JWT_TOKEN_TIME, LocalDateTime.now().toString());

       // builder.withExpiresAt(date);

        return builder.sign(Algorithm.HMAC256(SIGN));
    }

    public static String generateAccessToken(String phone, String identity) {
        return generateToken(phone, identity, TokenConstants.ACCESS_TOKEN_TYPE);
    }

    public static String generateRefreshToken(String phone, String identity) {
        return generateToken(phone, identity, TokenConstants.REFRESH_TOKEN_TYPE);
    }
    // 解析token
    public static TokenResult parseToken(String token) {
        // JWT.decode(token).getClaim(JWT_KEY).asString()
        // 指定 Algorithm 解析token

        TokenResult tokenResult = null;
        String phone = null;
        String identity = null;
        try {
            DecodedJWT verify = JWT.require(Algorithm.HMAC256(SIGN)).build().verify(token);
            phone = verify.getClaim(JWT_KEY_PHONE).asString();
            identity = verify.getClaim(JWT_KEY_IDENTITY).asString();
            tokenResult = new TokenResult(phone, identity);
        } catch (Exception e) {
            System.out.println("token解析异常");
        }
        return tokenResult;


    }

    public static void main(String[] args) {
        String token = generateToken("15179272574", "1", "accessToken");
        System.out.println("生成的token：" + token);
        System.out.println("解析token: " + parseToken(token));
    }
}
